package com.windoent.yugioh.ui.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Html;
import android.util.TypedValue;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentStatePagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.baidu.mobstat.StatService;
import com.tencent.mm.opensdk.modelbiz.WXLaunchMiniProgram;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.windoent.yugioh.MyApplication;
import com.windoent.yugioh.R;
import com.windoent.yugioh.adapter.GameManagerFragmentViewPagerAdapter;
import com.windoent.yugioh.adapter.banner.BannerImageAdapter;
import com.windoent.yugioh.base.BaseFragment;
import com.windoent.yugioh.bean.BannerBean;
import com.windoent.yugioh.bean.SaiShiListDataBean;
import com.windoent.yugioh.bean.UserBean;
import com.windoent.yugioh.bean.eventbus.SaiShiMessageEvent;
import com.windoent.yugioh.constants.Constants;
import com.windoent.yugioh.http.PhoneLive;
import com.windoent.yugioh.ui.activity.meinfo.MyMsgActivity;
import com.windoent.yugioh.ui.activity.saishi.CityPickerListActivity;
import com.windoent.yugioh.ui.activity.saishi.CreateGamesActivity;
import com.windoent.yugioh.ui.activity.saishi.SaiShiSearchActivity;
import com.windoent.yugioh.ui.fragment.saishi.shouye.HomeHasEndedFragment;
import com.windoent.yugioh.ui.fragment.saishi.shouye.HomeOnGoingFragment;
import com.windoent.yugioh.ui.fragment.saishi.shouye.HomeSignUpingFragment;
import com.windoent.yugioh.utils.BaseMethod;
import com.windoent.yugioh.utils.BaseUtils;
import com.windoent.yugioh.utils.LogUtils;
import com.windoent.yugioh.utils.TDevice;
import com.windoent.yugioh.utils.ToastUtils;
import com.windoent.yugioh.widget.MessageItem;
import com.windoent.yugioh.widget.ScaleTransitionPagerTitleView;
import com.windoent.yugioh.widget.SearchView;
import com.windoent.yugioh.widget.popupwindow.MeInfoAuthPopUpWindow;
import com.youth.banner.Banner;
import com.youth.banner.util.BannerUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import net.lucode.hackware.magicindicator.MagicIndicator;
import net.lucode.hackware.magicindicator.ViewPagerHelper;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.CommonNavigator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.CommonNavigatorAdapter;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerIndicator;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.abs.IPagerTitleView;
import net.lucode.hackware.magicindicator.buildins.commonnavigator.indicators.LinePagerIndicator;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * author : robert
 * date   : 2021/4/28 18:11
 * desc   :赛事
 */
public class SaiShiFragment extends BaseFragment implements View.OnClickListener {
    private int CITYNAMESELECT = 1;
    private LinearLayout mLlLocation;
    private TextView mTvLocation;
    private MessageItem mItemMsg;
    private Banner mBanner;
    private MagicIndicator mMagicIndicator;
    private ViewPager mViewpager;
    private LinearLayout mLlFiltrate;
    private LinearLayout mLlNodata;
    private RelativeLayout mRlContent;
    private ImageView mIvCreateGameDianjia;
    private SearchView mSearch;

    //标题头
    private List<String> fragmentsTitle = new ArrayList<>();
    private List<Fragment> fragments = new ArrayList<>();
    private GameManagerFragmentViewPagerAdapter pagerAdapter;
    private CommonNavigator commonNavigator;
    private SaiShiListDataBean.DataBean data;
    private BannerImageAdapter bannerImageAdapter;

    private String code;
    private String slectShai = "0";//全部

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_event;
    }

    public static SaiShiFragment newsInstance() {
        return new SaiShiFragment();
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        mLlLocation.setOnClickListener(this);
        mItemMsg.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                startActivity(new Intent(mContext, MyMsgActivity.class));
//                startXiaoChengxu();
            }
        });
        mLlFiltrate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                showFiltrate();
            }
        });
        mIvCreateGameDianjia.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                //创建比赛
                startActivity(new Intent(mContext, CreateGamesActivity.class));
            }
        });
        mSearch.setListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (BaseMethod.isNull(getUserToken())) {
                    BaseUtils.toLogIn(mContext, "");
                    return;
                }
                startActivity(new Intent(mContext, SaiShiSearchActivity.class));
            }
        });
    }

    //开启小程序
    private void startXiaoChengxu() {
        if (isWXAppInstalledAndSupported()) {
            String appId = Constants.APP_ID; // 填移动应用(App)的 AppId，非小程序的 AppID
            IWXAPI api = WXAPIFactory.createWXAPI(mContext, appId);

            WXLaunchMiniProgram.Req req = new WXLaunchMiniProgram.Req();
            req.userName = "gh_20f5d95c2cb0"; // 填小程序原始id
            req.path = "";                  ////拉起小程序页面的可带参路径，不填默认拉起小程序首页，对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"。
            req.miniprogramType = WXLaunchMiniProgram.Req.MINIPTOGRAM_TYPE_RELEASE;// 可选打开 开发版，体验版和正式版
            api.sendReq(req);
        }
    }


    //是否安装微信
    private boolean isWXAppInstalledAndSupported() {
        IWXAPI msgApi = WXAPIFactory.createWXAPI(mContext, null);
        msgApi.registerApp(Constants.APP_ID);
        return msgApi.isWXAppInstalled();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden && mLlNodata.getVisibility() == View.VISIBLE) {
            getSaiShiHomeListData();
        }
        if (!hidden) {
            if (mIvCreateGameDianjia != null) {
                String userInfo = MyApplication.getInstance().getUserInfo();
                if (BaseMethod.notNull(userInfo) && BaseUtils.isJSONValid(userInfo)) {
                    UserBean userBean = gson.fromJson(userInfo, UserBean.class);
                    if (userBean != null) {
                        boolean customer = userBean.isCustomer();
                        mIvCreateGameDianjia.setVisibility(customer ? View.VISIBLE : View.GONE);
                    }
                }
            }
            if (mItemMsg != null) {
                mItemMsg.setTvTitle(MyApplication.getInstance().getMsgNumber());
            }
            if (mTvLocation != null) {
                mTvLocation.setText(getCurrentLocation());
            }
        }
    }

    private void initData() {
        showNoData(false);
        getSaiShiHomeListData();
        initBannerAdapter();
        code = getCurrentLocationCode();
        MyApplication.cityCode = code;
        MyApplication.slectShai = slectShai;
    }

    private void initBannerAdapter() {
        bannerImageAdapter = new BannerImageAdapter(null);
        mBanner.setAdapter(bannerImageAdapter)
                .addBannerLifecycleObserver(this);//添加生命周期观察者
        mBanner.setBannerGalleryEffect(18, 10);
    }

    //赛事首页
    private void getSaiShiHomeListData() {
        showLoadingDialog("");
        PhoneLive.getSaiShiHomeListData(getUserToken(), "0", "0", "1", Constants.PAGETEN, "", new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                hideLoadingDialog();
                showNoData(true);
                ToastUtils.showText(e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                hideLoadingDialog();
                if (BaseUtils.isJSONValid(response)) {
                    try {
                        if (BaseUtils.codeIs0(mContext, response)) {
                            SaiShiListDataBean json = gson.fromJson(response, SaiShiListDataBean.class);
                            data = json.getData();
                            if (data != null) {
                                SaiShiListDataBean.DataBean.MatchStatusViewBean matchStatusView = data.getMatchStatusView();
                                List<BannerBean> bannerData = data.getBanner();
                                if (bannerData != null) {
                                    showNoData(false);
                                    if (mBanner != null) {
                                        mBanner.setVisibility(View.VISIBLE);
                                    }
                                    if (bannerImageAdapter != null) {
                                        bannerImageAdapter.setDatas(bannerData);
                                        bannerImageAdapter.notifyDataSetChanged();
                                    }
                                } else {
                                    if (mBanner != null) {
                                        mBanner.setVisibility(View.GONE);
                                    }
                                }
                                if (matchStatusView != null) {
                                    showNoData(false);
                                    //magic设置
                                    magic(matchStatusView);
                                } else showNoData(true);
                            } else showNoData(true);
                        } else showNoData(true);
                    } catch (JSONException e) {
                        showNoData(true);
                        e.printStackTrace();
                    }
                } else {
                    showNoData(true);
                    ToastUtils.showText(getString(R.string.string_response_error));
                }
            }
        });
    }

    private void initView() {
        mLlNodata = (LinearLayout) mView.findViewById(R.id.ll_nodata);
        mRlContent = (RelativeLayout) mView.findViewById(R.id.rl_content);

        mLlLocation = (LinearLayout) mView.findViewById(R.id.ll_location);
        mTvLocation = (TextView) mView.findViewById(R.id.tv_location);
        mItemMsg = (MessageItem) mView.findViewById(R.id.item_msg);
        mBanner = (Banner) mView.findViewById(R.id.banner);

        mMagicIndicator = (MagicIndicator) mView.findViewById(R.id.magicIndicator);
        mViewpager = (ViewPager) mView.findViewById(R.id.viewpager);
        mLlFiltrate = (LinearLayout) mView.findViewById(R.id.ll_filtrate);
        mIvCreateGameDianjia = (ImageView) mView.findViewById(R.id.iv_create_game_dianjia);

        mSearch = (SearchView) mView.findViewById(R.id.search);
    }

    @Override
    public void onClick(View view) {
        if (BaseMethod.isNull(getUserToken())) {
            BaseUtils.toLogIn(mContext, "");
            return;
        }
        int id = view.getId();
        if (id == R.id.ll_location) {
            Intent intent = new Intent(mContext, CityPickerListActivity.class);
            startActivityForResult(intent, CITYNAMESELECT);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && requestCode == CITYNAMESELECT) {
            if (data != null) {
                String cityName = data.getStringExtra("city_name");
                code = data.getStringExtra("city_code");
                LogUtils.d("cityCode--->:" + code);
                MyApplication.cityCode = code;
                mTvLocation.setText(cityName);
                sendBusMessage(slectShai, code);
            }
        }
    }

    private void magic(SaiShiListDataBean.DataBean.MatchStatusViewBean matchStatusView) {
        getInitData(matchStatusView);
        setMagicIndicator();
        if (pagerAdapter == null) {
            pagerAdapter = new GameManagerFragmentViewPagerAdapter(getChildFragmentManager(), FragmentStatePagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT, mContext, fragmentsTitle, fragments);
            if (mViewpager != null)
                //The application's PagerAdapter changed the adapter's contents without calling PagerAdapter
                if (mViewpager.getAdapter() != null) {
                    pagerAdapter.notifyDataSetChanged();
                } else
                    mViewpager.setAdapter(pagerAdapter);
        } else {
            pagerAdapter.notifyDataSetChanged();
        }
    }

    private void getInitData(SaiShiListDataBean.DataBean.MatchStatusViewBean matchStatusView) {
        if (fragmentsTitle != null) {
            fragmentsTitle.clear();
            fragmentsTitle.add(BaseMethod.notNullDefaultValue(matchStatusView.get_$2(), getString(R.string.string_registrstioning)));
            fragmentsTitle.add(BaseMethod.notNullDefaultValue(matchStatusView.get_$3(), getString(R.string.string_ongoing)));
            fragmentsTitle.add(BaseMethod.notNullDefaultValue(matchStatusView.get_$8(), getString(R.string.string_has_ended)));
        }
        if (fragments != null) {
            fragments.clear();
            fragments.add(HomeSignUpingFragment.newsInstance());
            fragments.add(HomeOnGoingFragment.newsInstance());
            fragments.add(HomeHasEndedFragment.newsInstance());
        }
    }


    private void setMagicIndicator() {
        if (commonNavigator == null) {
            commonNavigator = new CommonNavigator(mContext);
            commonNavigator.setAdjustMode(false);//均分
            CommonNavigatorAdapter adapterNavigstor = new CommonNavigatorAdapter() {
                @Override
                public int getCount() {
                    return fragmentsTitle == null ? 0 : fragmentsTitle.size();
                }

                @Override
                public IPagerTitleView getTitleView(Context context, int index) {
                    ScaleTransitionPagerTitleView titleView = new ScaleTransitionPagerTitleView(mContext);
                    titleView.setText(Html.fromHtml(fragmentsTitle.get(index)));
                    titleView.setNormalColor(Color.parseColor("#FFCCCCCC"));
                    titleView.setSelectedColor(Color.WHITE);
                    titleView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 20f);
                    titleView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            mViewpager.setCurrentItem(index, false);
                        }
                    });
                    return titleView;
                }

                @Override
                public IPagerIndicator getIndicator(Context context) {
                    LinePagerIndicator indicator = new LinePagerIndicator(mContext);
                    indicator.setMode(LinePagerIndicator.MODE_EXACTLY);
                    indicator.setLineHeight(TDevice.dp2px(mContext, 5));
                    indicator.setLineWidth(TDevice.dp2px(mContext, 30));
                    indicator.setRoundRadius(TDevice.dp2px(mContext, 6));
                    indicator.setStartInterpolator(new AccelerateInterpolator());
                    indicator.setEndInterpolator(new DecelerateInterpolator(2.0f));
                    indicator.setColors(Color.parseColor("#FFEC4E4E"));
                    return indicator;
                }
            };
            commonNavigator.setAdapter(adapterNavigstor);

            if (mMagicIndicator != null)
                mMagicIndicator.setNavigator(commonNavigator);
            if (mMagicIndicator != null && mViewpager != null)
                ViewPagerHelper.bind(mMagicIndicator, mViewpager);
        } else {
            commonNavigator.notifyDataSetChanged();
        }
    }

    //筛选
    private void showFiltrate() {
        if (data != null) {
            SaiShiListDataBean.DataBean.MatchTypeViewBean matchTypeView = data.getMatchTypeView();
            if (matchTypeView != null) {
                new MeInfoAuthPopUpWindow(mContext, getFiltData(matchTypeView), BannerUtils.dp2px(16), new MeInfoAuthPopUpWindow.OnInterface() {
                    @Override
                    public void onSelect(String s) {
                        //发送eventbus粘性事件
                        slectShai = getTypeFiltrate(s);
                        MyApplication.slectShai = slectShai;
                        sendBusMessage(slectShai, code);
                    }
                }).showAtBottom(mLlFiltrate, 0, 0);
            } else ToastUtils.showText(getString(R.string.string_no_data_filtrate));
        } else ToastUtils.showText(getString(R.string.string_no_data_filtrate));
    }

    //发送eventbus粘性事件
    private void sendBusMessage(String s, String code) {
        SaiShiMessageEvent event = new SaiShiMessageEvent();
        event.setMessage(s);
        event.setCode(code);
        event.setType(mViewpager.getCurrentItem());
        EventBus.getDefault().postSticky(event);
        LogUtils.d("0000----->:saishi");
    }

    //筛选类型
    private String getTypeFiltrate(String s) {
        if (BaseMethod.notNull(s) && s.equals("全部")) {
            return "0";
        }
        if (BaseMethod.notNull(s) && s.equals("娱乐赛")) {
            return "1";
        }
        if (BaseMethod.notNull(s) && s.equals("积分赛")) {
            return "2";
        }
        if (BaseMethod.notNull(s) && s.equals("特殊赛")) {
            return "3";
        }
        if (BaseMethod.notNull(s) && s.equals("巡回赛")) {
            return "4";
        }
        return "0";
    }

    //筛选数据
    private List<String> getFiltData(SaiShiListDataBean.DataBean.MatchTypeViewBean matchTypeView) {
        List<String> list = new ArrayList<>();
        list.clear();
        list.add(BaseMethod.notNullDefaultValue(matchTypeView.get_$0(), getString(R.string.string_all)));
        list.add(BaseMethod.notNullDefaultValue(matchTypeView.get_$1(), getString(R.string.string_entertainment_race)));
        list.add(BaseMethod.notNullDefaultValue(matchTypeView.get_$2(), getString(R.string.string_point_race)));
        list.add(BaseMethod.notNullDefaultValue(matchTypeView.get_$3(), getString(R.string.string_teshu_race)));
        list.add(BaseMethod.notNullDefaultValue(matchTypeView.get_$4(), getString(R.string.string_xunhui_race)));
        return list;
    }

    //无数据
    private void showNoData(boolean showNodata) {
        mLlNodata.setVisibility(showNodata ? View.VISIBLE : View.GONE);
        mRlContent.setVisibility(!showNodata ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        OkHttpUtils.getInstance().cancelTag(this);
        MyApplication.cityCode = getCurrentLocationCode();
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageEnd(getActivity(), "赛事首页列表");
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getActivity() != null) {
            // 页面埋点
            StatService.onPageStart(getActivity(), "赛事首页列表");
        }
        if (mIvCreateGameDianjia != null) {
            String userInfo = MyApplication.getInstance().getUserInfo();
            if (BaseMethod.notNull(userInfo) && BaseUtils.isJSONValid(userInfo)) {
                UserBean userBean = gson.fromJson(userInfo, UserBean.class);
                if (userBean != null) {
                    boolean customer = userBean.isCustomer();
                    mIvCreateGameDianjia.setVisibility(customer ? View.VISIBLE : View.GONE);
                }
            }
        }
        if (mItemMsg != null) {
            mItemMsg.setTvTitle(MyApplication.getInstance().getMsgNumber());
        }
        if (mTvLocation != null) {
            mTvLocation.setText(getCurrentLocation());
        }
    }
}
